import { useEffect, useState } from 'react';
import styles from './index.less';

export type ImageRadioOption = {
  label: string;
  value: string;
  image: string;
};

interface IImageRadioProps {
  passRadio?: (value?: ImageRadioOption) => void;
  options: ImageRadioOption[];
  value?: ImageRadioOption['value'];
  onChange?: (v: ImageRadioOption['value']) => void;
}

const ImageRadio: React.FunctionComponent<IImageRadioProps> = (props) => {
  const { options, value, onChange, passRadio } = props;
  const [newValue, setNewValue] = useState('');

  useEffect(() => {
    if (value) {
      setNewValue(value);
    }
  }, [value]);

  const clickHandle = (v: ImageRadioOption) => {
    onChange?.(v.value);
    passRadio?.(v);
  };
  return (
    <div className={styles.wrapper}>
      {options.map((opt) => (
        <div key={opt.value} className={styles['wrapper-item']} onClick={() => clickHandle(opt)}>
          <div
            className={`${styles['wrapper-item-image']} ${
              newValue === opt.value ? styles['wrapper-item-image-active'] : ''
            }`}
          >
            <img src={opt.image} />
          </div>
          <span>{opt.label}</span>
        </div>
      ))}
    </div>
  );
};

export default ImageRadio;
